<template>
  <div class="work-clothes-management">
    <div class="page-header">
      <h2>工服管理</h2>
      <el-button type="primary" @click="showAddWorkClothesDialog">
        <el-icon><Plus /></el-icon>
        添加工服
      </el-button>
    </div>
    
    <!-- 分组选择和搜索 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="工服名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入工服名称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <!-- 操作提示 -->
        <el-form-item>
          <el-alert
              title="操作结束后请手动点击载入底库"
              type="warning"
              show-icon
              :closable="false"
              style="margin-bottom: 0;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="warning" @click="handleLoadDatabase" :loading="loadingDatabase">
            <el-icon><Upload /></el-icon>
            载入底库
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 工服列表 -->
    <el-card shadow="never">
      <!-- 批量操作按钮 -->
      <div class="batch-actions" v-if="selectedWorkClothes.length > 0">
        <el-alert
          :title="`已选择 ${selectedWorkClothes.length} 个工服`"
          type="info"
          show-icon
          :closable="false"
        />
        <div class="batch-buttons">
          <el-button type="danger" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button @click="clearSelection">取消选择</el-button>
        </div>
      </div>
      
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="workClothes"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="200" show-overflow-tooltip />
        <el-table-column prop="name" label="名称" width="120" />

        <el-table-column prop="desc" label="描述" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.desc || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="`http://10.13.15.118/staticdata${row.image}`"
              :preview-src-list="[`http://10.13.15.118/staticdata${row.image}`]"
              :preview-teleported="true"
              fit="contain"
              style="width: 80px; height: 80px; border-radius: 4px; cursor: pointer;"
            />
            <span v-else class="text-gray">无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.update_time * 1000) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="showEditDialog(row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :prev-text="'上一页'"
          :next-text="'下一页'"
          :page-size-text="'条/页'"
          :total-text="'共 {total} 条'"
          :jumper-text="'前往'"
          :page-text="'页'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑工服对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑工服' : '添加工服'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="workClothesFormRef"
        :model="workClothesForm"
        :rules="workClothesRules"
        label-width="100px"
      >
        <el-form-item label="选择分组" prop="group_id">
          <el-select
            v-model="workClothesForm.group_id"
            placeholder="请选择分组"
            style="width: 100%"
          >
            <el-option
              v-for="group in groups"
              :key="group.id"
              :label="group.name"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="外部ID" prop="external_id">
          <el-input v-model="workClothesForm.external_id" placeholder="请输入外部ID" />
        </el-form-item>
        
        <el-form-item label="名称" prop="name">
          <el-input v-model="workClothesForm.name" placeholder="请输入工服名称" />
        </el-form-item>
        

        
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="workClothesForm.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息（可选）"
          />
        </el-form-item>
        
        <el-form-item label="上传图片" prop="image">
          <el-upload
            ref="uploadRef"
            class="work-clothes-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
            accept="image/jpeg,image/png"
          >
            <img v-if="imageUrl" :src="imageUrl" class="work-clothes-image" />
            <el-icon v-else class="work-clothes-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            只能上传 JPG 或 PNG 格式的图片，且不超过2MB
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 载入底库进度对话框 -->
    <el-dialog
      v-model="loadingDialogVisible"
      title="载入底库"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="loading-content">
        <el-progress :percentage="loadProgress" :status="loadStatus" />
        <p class="loading-text">{{ loadingText }}</p>
      </div>
      
      <template #footer>
        <el-button
          v-if="loadStatus === 'success' || loadStatus === 'exception'"
          type="primary"
          @click="loadingDialogVisible = false"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Upload,
  Delete
} from '@element-plus/icons-vue'
import {workClothesAPI} from '@/api'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const loadingDialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const loadingDatabase = ref(false)
const workClothesFormRef = ref()
const uploadRef = ref()
const tableRef = ref()
const imageUrl = ref('')
const imageFile = ref(null)

// 多选相关
const selectedWorkClothes = ref([])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 载入进度
const loadProgress = ref(0)
const loadStatus = ref('')
const loadingText = ref('')

// 数据列表
const workClothes = ref([])
const groups = ref([])

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 工服表单
const workClothesForm = reactive({
  id: '',
  group_id: '',
  external_id: '',
  name: '',
  desc: '',
  image: null
})

// 表单验证规则
const workClothesRules = {
  group_id: [
    { required: true, message: '请选择分组', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入工服名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  external_id: [
    { max: 100, message: '外部ID长度不能超过100个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 获取分组列表
const fetchGroups = async () => {
  try {
    const response = await workClothesAPI.getGroupInfo()
    
    // 检查响应数据结构
    const responseData = response.data || response
    
    if (responseData.error_code === 0 && responseData.data) {
      groups.value = responseData.data.map(group => ({
        id: group.id,
        name: group.name,
        alg: group.alg,
        ext: group.ext,
        update_time: group.update_time
      }))
      
      // 自动加载工服列表
      fetchWorkClothes()
    } else {
      groups.value = []
      const errorMsg = responseData.message?.zh || '获取分组列表失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
    ElMessage.error(`获取分组列表失败: ${error.message}`)
    groups.value = []
  }
}

// 获取工服列表
const fetchWorkClothes = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 如果有名称筛选，添加名称参数
    if (searchForm.name) {
      params.name = searchForm.name
    }
    
    const response = await workClothesAPI.getWorkClothesList(params)
    const responseData = response.data || response
    
    if (responseData.error_code === 0) {
      workClothes.value = responseData.data?.data || []
      total.value = responseData.data?.total || 0
    } else {
      workClothes.value = []
      total.value = 0
      const errorMsg = responseData.message?.zh || '获取工服列表失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('获取工服列表失败:', error)
    ElMessage.error(`获取工服列表失败: ${error.message}`)
    workClothes.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}



// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchWorkClothes()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  currentPage.value = 1
  fetchWorkClothes()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchWorkClothes()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchWorkClothes()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedWorkClothes.value = selection
}

const clearSelection = () => {
  tableRef.value.clearSelection()
}

// 显示添加工服对话框
const showAddWorkClothesDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(workClothesForm, {
    id: row.id,
    group_id: row.group_id,
    external_id: row.external_id || '',
    name: row.name || '',
    desc: row.desc || '',
    image: null
  })
  
  // 如果有图片，显示预览
  if (row.image) {
    imageUrl.value = `http://10.13.15.118/staticdata${row.image}`
  } else {
    imageUrl.value = ''
  }
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  if (workClothesFormRef.value) {
    workClothesFormRef.value.resetFields()
  }
  
  Object.assign(workClothesForm, {
    id: '',
    group_id: '',
    external_id: '',
    name: '',
    desc: '',
    image: null
  })
  
  imageUrl.value = ''
  imageFile.value = null
  
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 图片上传处理
const handleImageChange = (file) => {
  const isJPGOrPNG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
  const isLt2M = file.raw.size / 1024 / 1024 < 2
  
  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG 或 PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  
  imageFile.value = file.raw
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    imageUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
  
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!workClothesFormRef.value) return
  
  try {
    await workClothesFormRef.value.validate()
    
    submitLoading.value = true
    
    if (isEdit.value) {
      await updateWorkClothes()
    } else {
      await addWorkClothes()
    }
    
    dialogVisible.value = false
    fetchWorkClothes()
    ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 添加工服
const addWorkClothes = async () => {
  try {
    // 准备基本信息
    const workClothesData = {
      group_id: workClothesForm.group_id,
      external_id: workClothesForm.external_id,
      name: workClothesForm.name,
      desc: workClothesForm.desc
    }
    
    // 添加工服基本信息
    const response = await workClothesAPI.addWorkClothes(workClothesData)
    const responseData = response.data
    
    if (responseData.error_code !== 0) {
      throw new Error(responseData.message?.zh || '添加工服失败')
    }
    
    // 如果有图片，上传图片
    if (imageFile.value && responseData.data) {
      const formData = new FormData()
      formData.append('id', responseData.data)
      formData.append('image', imageFile.value)
      
      const imageResponse = await workClothesAPI.updateWorkClothesImage(formData)
      const imageResponseData = imageResponse.data || imageResponse
      
      if (imageResponseData.error_code !== 0) {
        console.warn('图片上传失败:', imageResponseData.message?.zh)
        ElMessage.warning('工服添加成功，但图片上传失败')
      }
    }
  } catch (error) {
    console.error('添加工服失败:', error)
    throw error
  }
}

// 更新工服
const updateWorkClothes = async () => {
  try {
    // 准备基本信息，过滤掉undefined的字段
    const workClothesData = {
      id: workClothesForm.id,
      group_id: workClothesForm.group_id,
      external_id: workClothesForm.external_id,
      name: workClothesForm.name,
      desc: workClothesForm.desc
    }
    
    // 过滤掉undefined的字段
    const filteredData = Object.fromEntries(
      Object.entries(workClothesData).filter(([_, value]) => value !== undefined)
    )
    
    // 更新工服基本信息
    const response = await workClothesAPI.updateWorkClothes(filteredData)
    const responseData = response.data || response
    
    if (responseData.error_code !== 0) {
      throw new Error(responseData.message?.zh || '更新工服信息失败')
    }
    
    // 如果有新图片，上传图片
    if (imageFile.value) {
      const formData = new FormData()
      formData.append('id', workClothesForm.id)
      formData.append('image', imageFile.value)
      
      const imageResponse = await workClothesAPI.updateWorkClothesImage(formData)
      const imageResponseData = imageResponse.data || imageResponse
      
      if (imageResponseData.error_code !== 0) {
        console.warn('图片更新失败:', imageResponseData.message?.zh)
        ElMessage.warning('工服信息更新成功，但图片更新失败')
      }
    }

  } catch (error) {
    console.error('更新工服失败:', error)
    throw error
  }
}

// 删除工服
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工服 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await workClothesAPI.deleteWorkClothes(row.id)
    const responseData = response.data || response
    
    if (responseData.error_code === 0) {
      ElMessage.success('删除成功')
      fetchWorkClothes()
    } else {
      const errorMsg = responseData.message?.zh || '删除失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除工服失败:', error)
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedWorkClothes.value.length === 0) {
    ElMessage.warning('请选择要删除的工服')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedWorkClothes.value.length} 个工服吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedWorkClothes.value.map(item => item.id)
    const response = await workClothesAPI.deleteWorkClothes(ids)
    const responseData = response.data || response
    
    if (responseData.error_code === 0) {
      ElMessage.success('批量删除成功')
      clearSelection()
      fetchWorkClothes()
    } else {
      const errorMsg = responseData.message?.zh || '批量删除失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除工服失败:', error)
      ElMessage.error(`批量删除失败: ${error.message}`)
    }
  }
}

// 载入底库
const handleLoadDatabase = async () => {
  try {
    loadingDatabase.value = true
    await workClothesAPI.loadDatabase()
    ElMessage.success('底库载入成功！')
  } catch (error) {
    console.error('载入底库失败:', error)
    ElMessage.error('载入底库失败，请稍后重试')
  } finally {
    loadingDatabase.value = false
  }
}
// 组件挂载时获取数据
onMounted(() => {
  fetchGroups()
})
</script>

<style scoped>

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.search-card .el-form-item:last-child {
  margin-left: auto;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.work-clothes-uploader {
  display: inline-block;
}

.work-clothes-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
  width: 148px;
  height: 148px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.work-clothes-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.work-clothes-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.work-clothes-image {
  width: 148px;
  height: 148px;
  object-fit: cover;
  display: block;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.loading-content {
  text-align: center;
}

.loading-text {
  margin-top: 16px;
  color: #606266;
}

.text-gray {
  color: #999;
}
</style>